import React from 'react';
import { Input, InputNumber, Form, Select } from 'antd';
import { isArray } from 'util';
import { EditableContext } from './EditableTableCustomTypes'; // 导入创建好的context对象

const FormItem = Form.Item;
const { Option } = Select;

class EditableCell extends React.Component {
  // 生成不同类型输入框（通过表头传入textType字段）
  getTextType = () => {
    const { customdata } = this.props;
    const textType = {
      input: <Input />,
      inputNumber: <InputNumber />,
      selectYesNo: <Select style={{ width: 120 }}>{this.handleSelectList(['是', '否'])}</Select>,
      selectEnable: (
        <Select style={{ width: 120 }}>{this.handleSelectList(['启用', '禁用'])}</Select>
      ),
      selectCustom: (
        <Select style={{ width: 120 }}>{this.handleSelectList(customdata, true)}</Select>
      ),
    };

    return textType[this.props.textType] || <Input />;
  };

  // 生成多个option下拉选项(循环数组, )
  /**
   * @param {Array} arrData 循环生成标签的数据
   * @param {Boolean} valueFlag 是否value值和内容一致？（默认value值使用索引值）
   * @description 描述: handleSelectList(['是', '否'], true)
   */
  handleSelectList = (arrData, valueFlag = false) => {
    const html = [];
    if (isArray(arrData)) {
      arrData.forEach((item, index) => {
        html.push(
          <Option value={valueFlag ? item : String(index)} key={item}>
            {item}
          </Option>
        );
      });
    }
    return html;
  };

  render() {
    const { editing, dataIndex, title, textType, record, index, ...restProps } = this.props;

    return (
      <EditableContext.Consumer>
        {form => {
          const { getFieldDecorator } = form;

          return (
            <td {...restProps}>
              {/* 判断可编辑状态显示输入框 */}
              {editing ? (
                <FormItem style={{ margin: 0 }}>
                  {getFieldDecorator(dataIndex, {
                    rules: [
                      {
                        required: true,
                        message: `${title}不能为空`,
                      },
                    ],
                    initialValue: record[dataIndex], // 默认值
                  })(this.getTextType())}
                </FormItem>
              ) : (
                restProps.children // 显示表格的内容，纯文字
              )}
            </td>
          );
        }}
      </EditableContext.Consumer>
    );
  }
}

export default EditableCell;
